import MySQLdb
import MySQLdb.cursors
import sys, os
sys.path.append(os.path.abspath("../"))
import servers
import sys
from pprint import pprint

host = servers.host
user = servers.user
passwd = servers.passwd
db_name = servers.db_name

db=MySQLdb.connect(host=host,user=user,passwd=passwd,db=db_name, cursorclass=MySQLdb.cursors.DictCursor)
c=db.cursor()



file_name = sys.argv[1]
sucursal = sys.argv[2]

print "HOST: ", host
print "SUCURSAL: ", sucursal
print "ARCHIVO: ",file_name

file = open(file_name, "r")

c.execute("start transaction")
i = 0
for l in file.readlines():

    try:
        cantidad = int(l.split(";")[1])
    except:
        cantidad = 1
        
    pprint(cantidad)

    try:
        ptc = l.split(";")[0]
        print "PTC"+str(ptc)+"aca"
        sql = "INSERT INTO stock (ptc, stock, sucursal) VALUES (%s, %s, %s)"
        #print "PROBLEEEEEEEEEEEEEEEEEEEMA"
        c.execute(sql, (str(ptc), cantidad, sucursal))
        #print sql
    except MySQLdb.IntegrityError:
        sql = "UPDATE stock SET stock = stock + %s WHERE ptc = %s AND sucursal = %s" 
        print sql
        c.execute(sql, (str(cantidad), str(ptc), sucursal))
        #print sql

c.execute("commit")
c.close()
db.close()
file.close()